<?php

if(!defined('IN_JANSEN')) {
    exit('Access Denied');
}

function getMyParam($param, $method='pg') {
    global $$param;
    if ( $method == 'pg' && ( isset($_POST[$param]) || isset($_GET[$param]) ) ) {
        $$param = ( isset($_POST[$param]) ) ? $_POST[$param] : $_GET[$param];
    }
    if ( $method == 'p' && isset($_POST[$param]) ) {
        $$param = $_POST[$param];
    }
    if ( $method == 'g' && isset($_GET[$param]) ) {
        $$param = $_GET[$param];
    }
    if ( $method == 'c' && isset($_COOKIE[$param]) ) {
        $$param = $_COOKIE[$param];
    }
    if ( $method == 's' && isset($_SESSION[$param]) ) {
        $$param = $_SESSION[$param];
    }
    if ( $method == 'r' && isset($_REQUEST[$param]) ) {
        $$param = $_REQUEST[$param];
    }
    if ( $method == 'f' && isset($_FILES[$param]) ) {
        $$param = $_FILES[$param];
    }
}

function daddslashes($string, $force = 0) {
    if(!$GLOBALS['magic_quotes_gpc'] || $force) {
        if(is_array($string)) {
            foreach($string as $key => $val) {
                $string[$key] = daddslashes($val, $force);
            }
        } else {
            $string = addslashes($string);
        }
    }
    return $string;
}

function dexit($message = '') {
    echo $message;
    //output();
    exit();
}

function debuginfo() {
    if($GLOBALS['debug']) {
        global $db, $starttime, $debuginfo, $debug_out;
        $mtime = explode(' ', microtime());
        $debuginfo = array('time' => number_format(($mtime[1] + $mtime[0] - $starttime), 6), 'queries' => $db->querynum);
        $debug_out = "Processed in " . $debuginfo['time'] . " second(s), " . $debuginfo['queries'] . " queries";
        return TRUE;
    } else {
        return FALSE;
    }
}

function Cookie($ck_Var,$ck_Value,$ck_Time='F'){
    global $cookietime,$cookiedomain,$cookiepath;
    if($ck_Time=='F') $ck_Time = $cookietime;
    $S=$_SERVER['SERVER_PORT']=='443' ? 1:0;
    setCookie($ck_Var,$ck_Value,$ck_Time,$cookiepath,$cookiedomain,$S);
}

function GetCookie($Var){
    if (isset($_COOKIE[$Var])) {
        return $_COOKIE[$Var];
    } else {
        return false;
    }
}

function getUnixTime($in_time) {
    //2000-01-01 10:00
    if (preg_match("/^([\d]{4})-([\d]{2})-([\d]{2})\s([\d]{2}):([\d]{2})$/i", $in_time, $match_array)) {
        return mktime($match_array[4], $match_array[5], 0, $match_array[2], $match_array[3], $match_array[1]);
    } else {
        return false;
    }
}

function getUnixTime2($in_time) {
    //2000-01-01
    if (preg_match("/^([\d]{4})-([\d]{1,2})-([\d]{1,2})$/i", $in_time, $match_array)) {
        return mktime(0, 0, 0, $match_array[2], $match_array[3], $match_array[1]);
    } else {
        return false;
    }
}


//function PrintEot($template,$EXT="htm"){
//    global $tplpath;
//    if(!$template) $template='N';
//    $path=JANSEN_ROOT."templates/$tplpath/$template.$EXT";
//    !file_exists($path) && $path=JANSEN_ROOT."templates/default/$template.$EXT";
////debug($path);
//    return $path;
//}
//by martin ʵֶ




function PrintEot($template,$EXT="htm"){
	
	global $tplpath;
    if(!$template) $template='N';
	$path=JANSEN_ROOT."templates/$tplpath/$template.$EXT";
    !file_exists($path) && $path=JANSEN_ROOT."templates/default/$template.$EXT";
//debug($path);
    return $path;
}

function PrintPrint($template,$EXT="htm"){
    global $tplpath;
    if(!$template) $template='N';
    $path=JANSEN_ROOT."templates/print/$template.$EXT";
    //!file_exists($path) && $path=JANSEN_ROOT."templates/default/$template.$EXT";
    return $path;
}

function readover($filename,$method="rb"){
    strpos($filename,'..')!==false && exit('Forbidden');
    if($handle=@fopen($filename,$method)){
        flock($handle,LOCK_SH);
        $filedata=@fread($handle,filesize($filename));
        fclose($handle);
    }
    return $filedata;
}

function writeover($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1){
   // $check && strpos($filename,'..')!==false && exit('Forbidden');
    touch($filename);
    $handle=fopen($filename,$method);
    if($iflock){
        flock($handle,LOCK_EX);
    }
    fwrite($handle,$data);
    if($method=="rb+") ftruncate($handle,strlen($data));
    fclose($handle);
    $chmod && @chmod($filename,0777);
}
function delPicture($file_name) {
    $file_path = JANSEN_ROOT . 'attachments/' . $file_name;
    if (file_exists($file_path)) {
        //@chmod($filename,0777);
        @unlink($file_path);
    }
}

function delSystemPicture($file_name) {
    $file_path = JANSEN_ROOT . 'attachments/system/' . $file_name;
    if (file_exists($file_path)) {
        //@chmod($filename,0777);
        @unlink($file_path);
    }
}

function ispage($number) {
    return !empty($number) && preg_match ("/^([0-9]+)$/", $number);
}

function getPageStr($total, $page, $perpage, $link) {
    $pages = @ceil($total / $perpage);
    $pagelink = '';
    if ($pages == 1) {
        $pagelink = "";
        return "";
    } elseif ($page == 1 && $page<$pages) {
        $pagelink = '<a href="' . $link . 'page=' . ($page+1) . '">></a> <a href="' . $link . 'page=' . $pages . 

'">>></a>';
    } elseif ($page<$pages) {
        $pagelink = '<a href="' . $link . 'page=1"><<</a> <a href="' . $link . 'page=' . ($page-1) . '"><</a> <a href="' 

. $link . 'page=' . ($page+1) . '">></a> <a href="' . $link . 'page=' . $pages . '">>></a>';
    } elseif ($page == $pages) {
        $pagelink = '<a href="' . $link . 'page=1"><<</a> <a href="' . $link . 'page=' . ($page-1) . '"><</a>';
    }

    $final_num = $page*$perpage < $total ? $page*$perpage : $total;
    return '<table width=100% align=center border=0 cellspacing=0 cellpadding=0 height=24>
              <tr>
                <td align=left>&nbsp;' . (($page-1)*$perpage+1) . ' - ' . $final_num . ' of ' . $total . ' records</td>
                <td align=right>&nbsp;&nbsp;&nbsp;' . $pagelink . '&nbsp;</td>
              </tr>
            </table>';
}

function getPhotoPageStr($total, $page, $perpage, $link, $show="products", $ext="") {
    $pages = @ceil($total / $perpage);
    $pagelink = '';

    //$page_str = "<span class='text_big2'>&nbsp;&nbsp;|&nbsp;$page&nbsp;|&nbsp;&nbsp;</span>";
	$page_str = "<span class='text_big2'>&nbsp;第&nbsp;$page&nbsp;页&nbsp;</span>";
    $final_num = $page*$perpage < $total ? $page*$perpage : $total;
    
	//$str = '你现正浏览 ' . $show . ' <strong>' . (($page-1)*$perpage+1) . '</strong> - <strong>' . 
$str = '你现正浏览 <strong>'.$total.'</strong> 个产品中的 <strong>'. (($page-1)*$perpage+1) . ' - ' . 
$final_num . '</strong>'. $ext . ' ';
    if ($pages == 1 && $page==$pages) {//echo $str;exit;
        $pagelink = "";
        return array('str'=>$str, 'pagelink'=>$page_str);
    } elseif ($page == 1 && $page<$pages) {
        $pagelink = $page_str . '&nbsp;&nbsp;&nbsp;<a href="' . $link . 'page=' . ($page+1) . '"><span 

class="text_big">></span></a>&nbsp;&nbsp;&nbsp;<a href="' . $link . 'page=' . $pages . '"><span 

class="text_big">>></span></a>';
    } elseif ($page<$pages) {
        $pagelink = '<a href="' . $link . 'page=1"><span class="text_big"><<</span></a>&nbsp;&nbsp;&nbsp;<a href="' . 

$link . 'page=' . ($page-1) . '"><span class="text_big"><</span></a>&nbsp;&nbsp;&nbsp;' . $page_str . 

'&nbsp;&nbsp;&nbsp;<a href="' . $link . 'page=' . ($page+1) . '"><span class="text_big">></span></a>&nbsp;&nbsp;&nbsp;<a 

href="' . $link . 'page=' . $pages . '"><span class="text_big">>></span></a>';
    } elseif ($page == $pages) {
        $pagelink = '<a href="' . $link . 'page=1"><span class="text_big"><<</span></a>&nbsp;&nbsp;&nbsp;<a href="' . 

$link . 'page=' . ($page-1) . '"><span class="text_big"><</span></a>&nbsp;&nbsp;&nbsp;' . $page_str;
    }


    //$str = (($page-1)*$perpage+1) . ' - ' . $final_num . ' of ' . $total . ' records&nbsp;&nbsp;' . $pagelink;
    return array('str'=>$str, 'pagelink'=>$pagelink);
}

//edit by martin for search
function SearchgetPhotoPageStr($total, $page, $perpage, $link, $show="products", $ext="") {
    $pages = @ceil($total / $perpage);
    $pagelink = '';

   
	$page_str = "<span class='text_big2'>&nbsp;第&nbsp;$page&nbsp;页&nbsp;</span>";
    $final_num = $page*$perpage < $total ? $page*$perpage : $total;    
	$str='您搜索了'.$ext.', 正在浏览第 <strong> '.(($page-1)*$perpage+1). ' - '.$final_num .' </strong> 条 / 共 <strong>'.$total.' </strong>条记录';
	
//$str = '你现正浏览 <strong>'.$total.'</strong> 个产品中的 '. (($page-1)*$perpage+1) . '</strong> - <strong>' . 
//$final_num . '</strong>'. $ext . ' .';
    if ($pages == 1 && $page==$pages) {//echo $str;exit;
        $pagelink = "";
        return array('str'=>$str, 'pagelink'=>$page_str);
    } elseif ($page == 1 && $page<$pages) {
        $pagelink = $page_str . '&nbsp;&nbsp;&nbsp;<a href="' . $link . 'page=' . ($page+1) . '"><span 

class="text_big">></span></a>&nbsp;&nbsp;&nbsp;<a href="' . $link . 'page=' . $pages . '"><span 

class="text_big">>></span></a>';
    } elseif ($page<$pages) {
        $pagelink = '<a href="' . $link . 'page=1"><span class="text_big"><<</span></a>&nbsp;&nbsp;&nbsp;<a href="' . 

$link . 'page=' . ($page-1) . '"><span class="text_big"><</span></a>&nbsp;&nbsp;&nbsp;' . $page_str . 

'&nbsp;&nbsp;&nbsp;<a href="' . $link . 'page=' . ($page+1) . '"><span class="text_big">></span></a>&nbsp;&nbsp;&nbsp;<a 

href="' . $link . 'page=' . $pages . '"><span class="text_big">>></span></a>';
    } elseif ($page == $pages) {
        $pagelink = '<a href="' . $link . 'page=1"><span class="text_big"><<</span></a>&nbsp;&nbsp;&nbsp;<a href="' . 

$link . 'page=' . ($page-1) . '"><span class="text_big"><</span></a>&nbsp;&nbsp;&nbsp;' . $page_str;
    }


    //$str = (($page-1)*$perpage+1) . ' - ' . $final_num . ' of ' . $total . ' records&nbsp;&nbsp;' . $pagelink;
    return array('str'=>$str, 'pagelink'=>$pagelink);
}


function setSystemValue($key, $value) {
    global $db;
	$sql = "SELECT COUNT(id) FROM `system` WHERE name='$key'";
	$r= $db->get_one($sql);
	if($r[0] > 0)
	{
		$sql = "UPDATE `system` SET `value` = '$value', `uptime` = '" . time() . "' WHERE name='$key'";
		$db->query($sql);
	}
	else
	{
		$sql = "INSERT INTO `system`(`name`,`value`, `uptime`) VALUES( '$key','$value','".time()."')";
		$db->query($sql);	
	}
	
    updateCache('system');
}

function getSystemValue($name) {
    global $cachedir, $db, $cache_updatetime, $timestamp;
    $_SYSTEM = array();   
	$cachedir="./zh/cache";
	//echo JANSEN_ROOTzh;
    //$file_name = JANSEN_ROOT . $cachedir . "/system_cache.php"; martin
	$file_name = JANSEN_ROOTzh . $cachedir . "/system_cache.php";
    if (!file_exists($file_name) || $timestamp-@filemtime($file_name) > $cache_updatetime*60) {
        updateCache('system');	
    }

    require_once($file_name);		
    if ($name == "")
	{
        return $_SYSTEM;
	
    } elseif (!isset($_SYSTEM[$name])) {
        return false;
    } else {
        return $_SYSTEM[$name];
    }
}


function updateCache($name) {
    global $cachedir, $db;
    $cachedir="./zh/cache";
	$file_name = JANSEN_ROOTzh . $cachedir . "/system_cache.php";
	//$file_name = JANSEN_ROOT . $cachedir . "/system_cache.php";
    $sql = "SELECT `name`,`valueen`, `valuezh` FROM `systemtb`";
    $query = $db->query($sql);
    while($rs = $db->fetch_array($query)) {
        $out_ary[] = $rs;
    }

    $tmp_str = "";

    foreach ($out_ary as $v) {
        $tmp_str .= "\$_SYSTEM['" . $v['name'] . "en'] = '" . $v['valueen'] . "';\r\n";
		$tmp_str .= "\$_SYSTEM['" . $v['name'] . "zh'] = '" . $v['valuezh'] . "';\r\n";
    }
    $tmp_str = "<?php\r\n" . $tmp_str . "?>";
    writeover($file_name, $tmp_str);
	

	//add by martin 2011 -01-25
	SystemAll_cache();
}

function checkLogin() {
    global $jansen_uid, $jansen_type, $jansen_status, $login_time, $timestamp, $cookietime;
    //echo $jansen_uid ;echo "<br>"; 
    //echo $jansen_type > 0;echo "<br>"; 
    //echo time() - $login_time;
	$url = $_SERVER["REQUEST_URI"];
	
    if ($jansen_uid > 0 && $jansen_type > 0 && time() - $login_time <= 1800) {
        Cookie("jansenuser",base64_encode($jansen_uid."\t".$jansen_type."\t".$jansen_status."\t".$timestamp), 

$cookietime); 
        
    } else {
    	Cookie('jansenuser','',0);
		header("Location:login.php?url=".base64_encode($url));
        exit;
    }
}

function getUserPrice($type) {
    return 'price_1';
}

function getPrice($jansen_type1, $inventorytype1, $price_ary, $sp) {
    //echo $jansen_type1 . "<hr>" . $inventorytype1;echo "<pre>";print_r($price_ary);
    if ($jansen_type1 == 1) {
        if ($inventorytype1 == 0) {
            return $price_ary['price_3'];
        } else {
            return $sp == 0 ? $price_ary['price_3'] : $sp;
        }

    } elseif ($jansen_type1 == 2) {
        if ($inventorytype1 == 0) {
            return $price_ary['price_2'] == 0 ? $price_ary['price_1'] : $price_ary['price_2'];
        } elseif ($inventorytype1 == 1) {
            return $sp == 0 ? $price_ary['price_1'] : $sp;
        } elseif ($inventorytype1 == 2) {
            return $sp == 0 ? $price_ary['price_2'] : $sp;
        }
    }

    return false;

}

function sendmail($from_name,$from_email,$to_name,$to_email,$subject,$content){
    
	$from     =   "MIME-Version:   1.0\n";   
	$from   .=   "Content-type:   text/html;   charset=utf-8\n";
	$from   .=   "From: ".$from_name."<".$from_email.">";
    if (strstr($to_email, ",")) {
        $tmp_ary = explode(",", $to_email);
		foreach ($tmp_ary as $v) {
			//$tmp_ary2[] = "$to_name <$v>";
			$to = "$to_name <$v>";
			@mail($to,$subject,$content,$from) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
        }
        //$to = implode(",", $tmp_ary2);
    } else {
        $to   = "$to_name <$to_email>";
		@mail($to,$subject,$content,$from) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
    }
    //@mail($to,$subject,$content,$from) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
	
	
	/*require_once("phpmailer/class.phpmailer.php"); 
	
	$mail = new PHPMailer(); 
	$mail->IsSMTP(); // send via SMTP 
	
	$mail->Host = "webmail.imakersolutions.com"; // SMTP servers 
	$mail->Username = "jansen@imakersolutions.com"; // SMTP username 
	$mail->Password = "JAN@imaker"; // SMTP password 	
	$mail->From = "jansen@imakersolutions.com"; //$from_email; // 
	
	$mail->FromName = $from_name; //
	$mail->SMTPAuth = true; // turn on SMTP authentication 	
	$mail->Port = 25; //default is 25, gmail is 465 or 587
	$mail->CharSet = "utf-8"; //
	$mail->Encoding = "base64"; 
	
	if (strstr($to_email, ",")) {
		$tmp_ary = explode(",", $to_email);
		foreach ($tmp_ary as $v) {
			$mail->AddAddress($v,$to_name);
		}	
	} else {
		$mail->AddAddress($to_email,$to_name);
	}	
	
	$mail->IsHTML(true); // send as HTML 
	//
	$mail->Subject = $subject;
	// 
	$mail->Body	= $content;
	if(!$mail->Send()) 
	{ 
		echo "Send mail error<p>"; 
		echo "Message: " . $mail->ErrorInfo; 
		exit; 
	}*/
}
//add by martin 2010-10-08
function sendhtmlmail2($from_name,$from_email,$to_name,$to_email,$subject,$content){
	//edit by maritn 2010 -10 -08
	$headers     =   "MIME-Version:   1.0\n";   
	$headers   .=   "Content-type:   text/html;   charset=utf-8\n";
	$headers   .=   "From: ".$from_name."<".$from_email.">";
	$from ="jansentest@imakersolutions.com";
	if (strstr($to_email, ",")) {
		$tmp_ary = explode(",", $to_email);
		foreach ($tmp_ary as $v) {
			//$tmp_ary2[] = "$to_name <$v>";
			$to = "$to_name <$v>";
			@mail($to,$subject,$content,$headers) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
		}
		//$to = implode(",", $tmp_ary2);
	} else {
		$to   = "$to_name <$to_email>";
		@mail($to,$subject,$content,$headers) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
	}
}

function sendhtmlmailCN($from_name,$from_email,$to_name,$to_email,$subject,$content,$attachment){
	
	
	    $filename="order.xls";
		$mimetype="application/vnd.ms-excel"; 
		$boundary = uniqid("");
		$headers="MIME-Version: 1.0\r\n";
		$headers = "content-type: multipart/mixed; boundary= $boundary\r\n";
		$headers.="From: ".$from_name."<".$from_email.">";
		$read=$attachment;
		//$read = base64_encode($attachment); 
		//$read = chunk_split($read); 	
		$body = "--$boundary
		content-type: text/html; charset=utf-8\r\ncontent-transfer-encoding: 8bit\r\n$content\r\n
		--$boundary
		content-type: $mimetype; name=$filename\r\n
		content-disposition: attachment; filename=$filename\r\n
		content-transfer-encoding: base64\r\n$read\r\n
		--$boundary--"; 		


	$to_name = "=?utf-8?B?".base64_encode($to_name)."?=";	
	if (strstr($to_email, ",")) {
		$tmp_ary = explode(",", $to_email);
		foreach ($tmp_ary as $v) {		
			$to = "$to_name <$v>";
			@mail($to,$subject,$content,$headers) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
		}	
	} else {
		$to   = "$to_name <$to_email>";
		@mail($to,$subject,$content,$headers) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
	}

}



function sendhtmlmailCN2($from_name,$from_email,$to_name,$to_email,$subject,$content,$attachment){

     $headers="MIME-Version: 1.0\r\n";
	 $headers.="Content-type: text/html;charset=utf-8\r\n";  
	 $headers.="Content-Transfer-Encoding: 8bit\r\n";
	 $to_name = "=?utf-8?B?".base64_encode($to_name)."?=";
	 $headers.="From: ".$from_name."<".$from_email.">";
	//$from    =   "MIME-Version:   1.0\r\n"; 
	//$from   .=   "Content-type:   text/html;   charset=utf-8\r\n";	
	//$from   .= "Content-Transfer-Encoding: 8bit\r\n";
	//$from   .= "From: ".$from_name."<".$from_email.">";
	
	//$subject = base64_encode($subject);
	//$subject="MANAGER";

	
	if (strstr($to_email, ",")) {
		$tmp_ary = explode(",", $to_email);
		foreach ($tmp_ary as $v) {		
			$to = "$to_name <$v>";
			@mail($to,$subject,$content,$headers) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
		}
		//$to = implode(",", $tmp_ary2);
	} else {
		$to   = "$to_name <$to_email>";
		@mail($to,$subject,$content,$headers) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
	}

}


function sendhtmlmail($from_name,$from_email,$to_name,$to_email,$subject,$content){

	$from     =   "MIME-Version:   1.0\n";   
	$from   .=   "Content-type:   text/html;   charset=utf-8\n";
	$from   .= "From: ".$from_name."<".$from_email.">";
	
	
	$headers = "MIME-Version: 1.0" . "\n";
    $headers .= "Content-type:text/html;charset=utf-8"."\n"; 
	$headers .="From: ".$from_name."<".$from_email.">"."\n";
	//$headers .= "From: <info@jansenfurnitrue.com.cn>"."\n";
	$headers .= "Content-Transfer-Encoding: base64";
	$content = base64_encode($content);
	
	//$subject = stripslashes($subject);
	//$subject = "=?UTF-8?B?".base64_encode($subject)."?=";
	 $to_name = "=?utf-8?B?".base64_encode($to_name)."?=";
	if (strstr($to_email, ",")) {
		$tmp_ary = explode(",", $to_email);
		foreach ($tmp_ary as $v) {
			//$tmp_ary2[] = "$to_name <$v>";
			$to = "$to_name <$v>";
			//@mail($to,$subject,$content,$from) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
			@mail($to,$subject,$content,$headers) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
		}
		//$to = implode(",", $tmp_ary2);
	} else {
		$to   = "$to_name <$to_email>";
		//@mail($to,$subject,$content,$from) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
		@mail($to,$subject,$content,$from) or die("<h2 align=\"center\">Something must wrong, please contact the webmaster.</h2>");
	}

}

function getExt($filename) {
    if (strstr($filename, ".")) {
        $tmp_ary = explode(".", $filename);
        return array_pop($tmp_ary);
        //return substr(strrchr($file, "."), 1);
    }

    return false;
}

function setStatus($flag) {
    global $jansen_type, $page_title, $page_guide_pic, $menu_id, $special_flag, $sql_2, $sql_3, $page_guide_name,

$page_guide_name2,$page_special_pic;
    $special_flag=$sql_2='';
    $sql_3=' AND i.`inventory_id` = n.`id` ';


    if ($flag) {
        $page_title = 'jans2en furniture - Specials - Specials';
        $page_guide_name = 'Specials';
        $page_guide_name2 = '<a href="inventory.php?special=1">Specials</a>';
        $page_guide_pic = $page_special_pic;
        $menu_id = 8;
        $special_flag = '&special=1';
        $sql_2 = ' AND i.`special_price`>0 ';
        $sql_3 = ' AND i.`inventory_id` = n.`id` ';

        if ($jansen_type==2) {
            $sql_2 = ' AND i.`special_price`>0 ';
        } elseif ($jansen_type == 1) {
            $sql_2 = ' AND i.`special_price2`>0 ';
        }
    }
}


function br2br($str, $add, $len) {
    if (strlen($str) > $len) {
        $str1 = substr($str, 0, $len);
        $str2 = substr($str, $len, 1);
        $str3 = substr($str, $len+1);
       // /*
        //var_dump($str1); echo "<hr>";
        //var_dump($str2);echo "<hr>";
        //var_dump($str3);echo "<hr>";
        //exit;
       // */
        if ($str2 != " " && $str2 != " ") {
            $str4 = substr(strrchr($str1, " "), 1);
            //var_dump($str4);exit;
            if (!$str4) {
                return $str1 . $add . $str2 . $str3;
            } else {
                return str_replace($str4, $add . $str4, $str1) . $str2 . $str3;
            }
            //exit;
        } else {
            //if (substr($str, $len-1, 1) == '&') {
                //return $str1 . "<br>" . $add . $str3;
            //} else {
                return $str1 . $add . $str3;
            //}
        }
    } else {
        return $str;
    }
}

// תΪ ent2ncr 
function ent2ncr($text) {
    $to_ncr = array(
    '&quot;' => '&#34;',
    '&amp;' => '&#38;',
    '&frasl;' => '&#47;',
    '&lt;' => '&#60;',
    '&gt;' => '&#62;',
    '|' => '&#124;',
    '&nbsp;' => '&#160;',
    '&iexcl;' => '&#161;',
    '&cent;' => '&#162;',
    '&pound;' => '&#163;',
    '&curren;' => '&#164;',
    '&yen;' => '&#165;',
    '&brvbar;' => '&#166;',
    '&brkbar;' => '&#166;',
    '&sect;' => '&#167;',
    '&uml;' => '&#168;',
    '&die;' => '&#168;',
    '&copy;' => '&#169;',
    '&ordf;' => '&#170;',
    '&laquo;' => '&#171;',
    '&not;' => '&#172;',
    '&shy;' => '&#173;',
    '&reg;' => '&#174;',
    '&macr;' => '&#175;',
    '&hibar;' => '&#175;',
    '&deg;' => '&#176;',
    '&plusmn;' => '&#177;',
    '&sup2;' => '&#178;',
    '&sup3;' => '&#179;',
    '&acute;' => '&#180;',
    '&micro;' => '&#181;',
    '&para;' => '&#182;',
    '&middot;' => '&#183;',
    '&cedil;' => '&#184;',
    '&sup1;' => '&#185;',
    '&ordm;' => '&#186;',
    '&raquo;' => '&#187;',
    '&frac14;' => '&#188;',
    '&frac12;' => '&#189;',
    '&frac34;' => '&#190;',
    '&iquest;' => '&#191;',
    '&Agrave;' => '&#192;',
    '&Aacute;' => '&#193;',
    '&Acirc;' => '&#194;',
    '&Atilde;' => '&#195;',
    '&Auml;' => '&#196;',
    '&Aring;' => '&#197;',
    '&AElig;' => '&#198;',
    '&Ccedil;' => '&#199;',
    '&Egrave;' => '&#200;',
    '&Eacute;' => '&#201;',
    '&Ecirc;' => '&#202;',
    '&Euml;' => '&#203;',
    '&Igrave;' => '&#204;',
    '&Iacute;' => '&#205;',
    '&Icirc;' => '&#206;',
    '&Iuml;' => '&#207;',
    '&ETH;' => '&#208;',
    '&Ntilde;' => '&#209;',
    '&Ograve;' => '&#210;',
    '&Oacute;' => '&#211;',
    '&Ocirc;' => '&#212;',
    '&Otilde;' => '&#213;',
    '&Ouml;' => '&#214;',
    '&times;' => '&#215;',
    '&Oslash;' => '&#216;',
    '&Ugrave;' => '&#217;',
    '&Uacute;' => '&#218;',
    '&Ucirc;' => '&#219;',
    '&Uuml;' => '&#220;',
    '&Yacute;' => '&#221;',
    '&THORN;' => '&#222;',
    '&szlig;' => '&#223;',
    '&agrave;' => '&#224;',
    '&aacute;' => '&#225;',
    '&acirc;' => '&#226;',
    '&atilde;' => '&#227;',
    '&auml;' => '&#228;',
    '&aring;' => '&#229;',
    '&aelig;' => '&#230;',
    '&ccedil;' => '&#231;',
    '&egrave;' => '&#232;',
    '&eacute;' => '&#233;',
    '&ecirc;' => '&#234;',
    '&euml;' => '&#235;',
    '&igrave;' => '&#236;',
    '&iacute;' => '&#237;',
    '&icirc;' => '&#238;',
    '&iuml;' => '&#239;',
    '&eth;' => '&#240;',
    '&ntilde;' => '&#241;',
    '&ograve;' => '&#242;',
    '&oacute;' => '&#243;',
    '&ocirc;' => '&#244;',
    '&otilde;' => '&#245;',
    '&ouml;' => '&#246;',
    '&divide;' => '&#247;',
    '&oslash;' => '&#248;',
    '&ugrave;' => '&#249;',
    '&uacute;' => '&#250;',
    '&ucirc;' => '&#251;',
    '&uuml;' => '&#252;',
    '&yacute;' => '&#253;',
    '&thorn;' => '&#254;',
    '&yuml;' => '&#255;',
    '&OElig;' => '&#338;',
    '&oelig;' => '&#339;',
    '&Scaron;' => '&#352;',
    '&scaron;' => '&#353;',
    '&Yuml;' => '&#376;',
    '&fnof;' => '&#402;',
    '&circ;' => '&#710;',
    '&tilde;' => '&#732;',
    '&Alpha;' => '&#913;',
    '&Beta;' => '&#914;',
    '&Gamma;' => '&#915;',
    '&Delta;' => '&#916;',
    '&Epsilon;' => '&#917;',
    '&Zeta;' => '&#918;',
    '&Eta;' => '&#919;',
    '&Theta;' => '&#920;',
    '&Iota;' => '&#921;',
    '&Kappa;' => '&#922;',
    '&Lambda;' => '&#923;',
    '&Mu;' => '&#924;',
    '&Nu;' => '&#925;',
    '&Xi;' => '&#926;',
    '&Omicron;' => '&#927;',
    '&Pi;' => '&#928;',
    '&Rho;' => '&#929;',
    '&Sigma;' => '&#931;',
    '&Tau;' => '&#932;',
    '&Upsilon;' => '&#933;',
    '&Phi;' => '&#934;',
    '&Chi;' => '&#935;',
    '&Psi;' => '&#936;',
    '&Omega;' => '&#937;',
    '&alpha;' => '&#945;',
    '&beta;' => '&#946;',
    '&gamma;' => '&#947;',
    '&delta;' => '&#948;',
    '&epsilon;' => '&#949;',
    '&zeta;' => '&#950;',
    '&eta;' => '&#951;',
    '&theta;' => '&#952;',
    '&iota;' => '&#953;',
    '&kappa;' => '&#954;',
    '&lambda;' => '&#955;',
    '&mu;' => '&#956;',
    '&nu;' => '&#957;',
    '&xi;' => '&#958;',
    '&omicron;' => '&#959;',
    '&pi;' => '&#960;',
    '&rho;' => '&#961;',
    '&sigmaf;' => '&#962;',
    '&sigma;' => '&#963;',
    '&tau;' => '&#964;',
    '&upsilon;' => '&#965;',
    '&phi;' => '&#966;',
    '&chi;' => '&#967;',
    '&psi;' => '&#968;',
    '&omega;' => '&#969;',
    '&thetasym;' => '&#977;',
    '&upsih;' => '&#978;',
    '&piv;' => '&#982;',
    '&ensp;' => '&#8194;',
    '&emsp;' => '&#8195;',
    '&thinsp;' => '&#8201;',
    '&zwnj;' => '&#8204;',
    '&zwj;' => '&#8205;',
    '&lrm;' => '&#8206;',
    '&rlm;' => '&#8207;',
    '&ndash;' => '&#8211;',
    '&mdash;' => '&#8212;',
    '&lsquo;' => '&#8216;',
    '&rsquo;' => '&#8217;',
    '&sbquo;' => '&#8218;',
    '&ldquo;' => '&#8220;',
    '&rdquo;' => '&#8221;',
    '&bdquo;' => '&#8222;',
    '&dagger;' => '&#8224;',
    '&Dagger;' => '&#8225;',
    '&bull;' => '&#8226;',
    '&hellip;' => '&#8230;',
    '&permil;' => '&#8240;',
    '&prime;' => '&#8242;',
    '&Prime;' => '&#8243;',
    '&lsaquo;' => '&#8249;',
    '&rsaquo;' => '&#8250;',
    '&oline;' => '&#8254;',
    '&frasl;' => '&#8260;',
    '&euro;' => '&#8364;',
    '&image;' => '&#8465;',
    '&weierp;' => '&#8472;',
    '&real;' => '&#8476;',
    '&trade;' => '&#8482;',
    '&alefsym;' => '&#8501;',
    '&crarr;' => '&#8629;',
    '&lArr;' => '&#8656;',
    '&uArr;' => '&#8657;',
    '&rArr;' => '&#8658;',
    '&dArr;' => '&#8659;',
    '&hArr;' => '&#8660;',
    '&forall;' => '&#8704;',
    '&part;' => '&#8706;',
    '&exist;' => '&#8707;',
    '&empty;' => '&#8709;',
    '&nabla;' => '&#8711;',
    '&isin;' => '&#8712;',
    '&notin;' => '&#8713;',
    '&ni;' => '&#8715;',
    '&prod;' => '&#8719;',
    '&sum;' => '&#8721;',
    '&minus;' => '&#8722;',
    '&lowast;' => '&#8727;',
    '&radic;' => '&#8730;',
    '&prop;' => '&#8733;',
    '&infin;' => '&#8734;',
    '&ang;' => '&#8736;',
    '&and;' => '&#8743;',
    '&or;' => '&#8744;',
    '&cap;' => '&#8745;',
    '&cup;' => '&#8746;',
    '&int;' => '&#8747;',
    '&there4;' => '&#8756;',
    '&sim;' => '&#8764;',
    '&cong;' => '&#8773;',
    '&asymp;' => '&#8776;',
    '&ne;' => '&#8800;',
    '&equiv;' => '&#8801;',
    '&le;' => '&#8804;',
    '&ge;' => '&#8805;',
    '&sub;' => '&#8834;',
    '&sup;' => '&#8835;',
    '&nsub;' => '&#8836;',
    '&sube;' => '&#8838;',
    '&supe;' => '&#8839;',
    '&oplus;' => '&#8853;',
    '&otimes;' => '&#8855;',
    '&perp;' => '&#8869;',
    '&sdot;' => '&#8901;',
    '&lceil;' => '&#8968;',
    '&rceil;' => '&#8969;',
    '&lfloor;' => '&#8970;',
    '&rfloor;' => '&#8971;',
    '&lang;' => '&#9001;',
    '&rang;' => '&#9002;',
    '&larr;' => '&#8592;',
    '&uarr;' => '&#8593;',
    '&rarr;' => '&#8594;',
    '&darr;' => '&#8595;',
    '&harr;' => '&#8596;',
    '&loz;' => '&#9674;',
    '&spades;' => '&#9824;',
    '&clubs;' => '&#9827;',
    '&hearts;' => '&#9829;',
    '&diams;' => '&#9830;'
    );

    return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
}

// ¼ûʵҳϢ
function browseTracking($action, $aid=0, $details, $settime = '600') {
    /*
//    * action: $browse_tracking_ary = array(1=>'Login', 2=>'About us', 3=>'Products', 4=>'Inventory', 5=>'Tradeshow', 

6=>'Search', 7=>'Gallery');
//    * aid: ӦactionactionΪ3ʱ¼ʱĲƷid
//    * details: Ϣ
//    * date: ʱ
//    * settime: ¼ͬһĬ600m
//    */
	$froms="CN";
    global $db, $timestamp, $jansen_uid;
    
    if (isset($jansen_uid) && $jansen_uid>0) {
        
        if ($action == 6) {
            $sql = "select id from browse_tracking where `uid`='$jansen_uid' and `action`='$action' and `aid`='$aid' and 

`details`='$details' and `date`>($timestamp-$settime)";
        } else {
            $sql = "select id from browse_tracking where `details`='$details' and `uid`='$jansen_uid' and 

`action`='$action' and `aid`='$aid' and `date`>($timestamp-$settime)";
        }
        $row = $db->get_one($sql);
        if (empty($row)) {
            $sql = "insert into browse_tracking (`uid`, `action`, `aid`, `details`, `date`,`from`) values ('$jansen_uid', 

'$action', '$aid', '$details', '$timestamp','$froms')";
            @$db->query($sql);
        }     
    } 
}

// ¼ûʵ¼Ϣ
function browseTracking_login($jansen_uid) {

    global $db, $timestamp;
    
	$froms="CN";
    if ($jansen_uid>0) {
        
        $sql = "select id from browse_tracking where `uid`='$jansen_uid' and `action`='1' and `aid`='0' and `date`>

($timestamp-600)";
        $row = $db->get_one($sql);
        if (empty($row)) {
			$sql = "insert into browse_tracking (`uid`, `action`, `aid`, `details`, `date`,`from`) values ('$jansen_uid', '1', 
					
					'0', 'Login', '$timestamp','$froms')";
            @$db->query($sql);
        }
    }
}


function saveCart($db, $jansen_uid, $cart) {
	global $timestamp;

	if ($jansen_uid>0) {
		if (!empty($cart)) {

			$sql = "SELECT cart FROM cart_record WHERE `uid`='$jansen_uid'";
			$cart_info_ary = $db->get_one($sql);
			if (empty($cart_info_ary) || empty($cart_info_ary['cart'])) {
				$sql2 = "SELECT * FROM `user` WHERE `id`='$jansen_uid'";
				$user_info_ary = $db->get_one($sql2);
				$dealer_name = trim($user_info_ary['lastname']) != '' ? $user_info_ary['firstname'] . ' ' 

. $user_info_ary['lastname'] : $user_info_ary['firstname'];
				$dealer_company = trim($user_info_ary['company']);
				
				$system_ary = getSystemValue("");
				$webmaster_name = $system_ary['webmaster_namezh'];
				$webmaster_email = $system_ary['webmaster_emailzh'];             
				require_once './mail/alert_order_to_webmaster.php'; 				
				//sendhtmlmail($from_name,$from_email,$to_name,$to_email,$subject,$content);
			}

			$cart_r = serialize($cart);
			$sql = "replace into cart_record (`uid`, `cart`, `date`) values ('$jansen_uid', '" . $cart_r . 

"', '$timestamp')";
		} else {
			$sql = "replace into cart_record (`uid`, `cart`, `date`) values ('$jansen_uid', '', 

'$timestamp')";
		}
        @$db->query($sql);
	}
}
if(!function_exists('json_encode')) {
	function json_encode($arg) {
		$returnValue = '';
		$c           = '';
		$i           = '';
		$l           = '';
		$s           = '';
		$v           = '';
		$numeric     = true;
		
		switch (gettype($arg)) {
			case 'array':
				foreach ($arg AS $i => $v) {
					if (!is_numeric($i)) {
						$numeric = false;
						break;
					}
				}
				
				if ($numeric) {
					foreach ($arg AS $i => $v) {
						if (strlen($s) > 0) {
							$s .= ',';
						}
						$s .= json_encode($arg[$i]);
					}
					
					$returnValue = '[' . $s . ']';
				} else {
					foreach ($arg AS $i => $v) {
						if (strlen($s) > 0) {
							$s .= ',';
						}
						$s .= json_encode($i) . ':' . json_encode($arg[$i]);
					}
					
					$returnValue = '{' . $s . '}';
				}
				break;
			
			case 'object':
				foreach (get_object_vars($arg) AS $i => $v) {
					$v = json_encode($v);
					
					if (strlen($s) > 0) {
						$s .= ',';
					}
					$s .= json_encode($i) . ':' . $v;
				}
				
				$returnValue = '{' . $s . '}';
				break;
			
			case 'integer':
			case 'double':
				$returnValue = is_numeric($arg) ? (string) $arg : 'null';
				break;
			
			case 'string':
				$returnValue = '"' . strtr($arg, array(
							"\r"   => '\\r',    "\n"   => '\\n',    "\t"   => '\\t',     "\b" 

  => '\\b',
							"\f"   => '\\f',    '\\'   => '\\\\',   '"'    => '\"',
							"\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002', 

"\x03" => '\u0003',
							"\x04" => '\u0004', "\x05" => '\u0005', "\x06" => '\u0006', 

"\x07" => '\u0007',
							"\x08" => '\b',     "\x0b" => '\u000b', "\x0c" => '\f',     

"\x0e" => '\u000e',
							"\x0f" => '\u000f', "\x10" => '\u0010', "\x11" => '\u0011', 

"\x12" => '\u0012',
							"\x13" => '\u0013', "\x14" => '\u0014', "\x15" => '\u0015', 

"\x16" => '\u0016',
							"\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019', 

"\x1a" => '\u001a',
							"\x1b" => '\u001b', "\x1c" => '\u001c', "\x1d" => '\u001d', 

"\x1e" => '\u001e',
							"\x1f" => '\u001f'
							)) . '"';
				break;
			
			case 'boolean':
				$returnValue = $arg?'true':'false';
				break;
			
			default:
				$returnValue = 'null';
		}
		
		return $returnValue;
	}
}
//$aryCate:Ʒ,$l:𼶱,$lshow:Ҫʾļ(0޼)
function GetMenu_ProductCate($aryCate,$l,$lshow,$toPageUrl)
{
 
	$s = '<ul class="u'.$l.'">';
	foreach($aryCate as $k=>$v)
	{
		if($v["publish"]==0 || GetProductNum($v) <=0 ) continue; //ǲ²ƷΪ0,ʾ		
		//add by martin for set englist text arial

		$v["namezh"]=AddAiralStyle($v["namezh"]);
		//echo $v["namezh"];
		
		$s.='<li id="li1_'.$l.'_'.$v["id"].'"><a href="'.$toPageUrl.'?categoryid='.$v["id"].'&fid='.$v["fid"].'" class="a'.$l.'">'.$v["namezh"].'</a>';
		if(is_array($v["sub_cate"]) && count($v["sub_cate"]) > 0)
		{
			if($lshow > 0 && $l>=$lshow) continue;
			$s.=GetMenu_ProductCate($v["sub_cate"],$l+1,$lshow,$toPageUrl);
		}
		$s.='</li>';
	}
	$s.='</ul>';
	
	return $s;
}
//$aryCate:,$l:𼶱,$toPageFormat:Ҫʾĵַʽ,˳Ϊcategoryid,settingid
function GetMenu_SettingCate($aryCate,$l,$toPageFormat)
{
	$s = '<ul class="u'.$l.'">';
	foreach($aryCate as $k=>$v)
	{
		if($v["publish"]==0) continue; //ǲ,ʾ
		//add by martin for set englist text arial
		$v["namezh"]=AddAiralStyle($v["namezh"]);
		
		$s.='<li id="li2_'.$l.'_'.$v["id"].'"><a href="'.sprintf($toPageFormat,$v["id"],0).'" class="a'.$l.'">'.$v["namezh"].'</a>';
		if(isset($v["setting"])&&is_array($v["setting"]) && count($v["setting"]) > 0)
		{
			$s .='<ul class="u'.($l+1).'">';
			foreach($v["setting"] as $kk=>$vv)
			{
				$s.='<li id="li2_'.($l+1).'_s'.$v["id"].'"><a href="'.sprintf($toPageFormat,$v["id"],$vv["id"]).'" class="a'.($l+1).'">'.$vv["namezh"].'</a>';
			}
			$s .= '</ul>';
		}
		$s.='</li>';
	}
	$s.='</ul>';
	
	return $s;
}

//$li_id: liԪid,$aryData:ʾ,$sFormatӴʽ
function GetMenuShow($li_id,$aryData,$sFormat,$l)
{
	$s = '<ul class="u'.$l.'">';
	foreach($aryData as $k=>$v)
	{
	
		if($v["ispublish"]==0) continue; //ǲ,ʾ
		
		//add by martin for set englist text arial
		$v["namezh"]=AddAiralStyle($v["namezh"]);
		
		$s.='<li id="'.$li_id.'_'.$l.'_'.$v["id"].'"><a href="'.sprintf($sFormat,$v["id"]).'" class="a'.$l.'">'.$v["namezh"].'</a>';		
		$s.='</li>';
	}
	$s.='</ul>';
	
	return $s;
}


// this for style menu  edit by martin 2011-04-21
function GetCategoryTableStyle($aryData,$sFormat,$l,$SelectedID,$ParentID,&$flagAry)
{
	$s = '';
	$dot = '';
	$sep = '';
	$name = '';
	$display = '';
	$cateStyle = ''; 
	$title='';
	if($flagAry == null) $flagAry = array(); 
	
	for($i=0;$i<$l;$i++)
	{
		$sep .= '&nbsp;&nbsp;&nbsp;&nbsp;';	
	}
	
	if($ParentID == 0) $cateStyle = "menu_list";
	else  $cateStyle = "menu_list_sub";
	
	foreach($aryData as $k=>$v)
	{
		if(array_key_exists("publish",$v) && $v["publish"]==0 ) continue; 
		if(array_key_exists("ispublish",$v) && $v["ispublish"]==0) continue; 		
		if(array_key_exists("sub_cate",$v) && GetProductNum($v) <=0 ) continue; 	
	
		if(isset($v["descriptionzh"])&&$v["descriptionzh"]!="")
		{
			$title='title="'.$v["descriptionzh"].'"';
		}else{
			$title='';
		}
		
		
		if($v["id"]==$SelectedID)
		{
			$name='<font color="#b68f2e" >'.$v["namezh"].'</font>';
			$flagAry[$ParentID] = $v["id"];
		}
		else
		{
			$name = $v["namezh"];	
		}
		
		
		
		if(array_key_exists("fid",$v))
		{
			$s .='<tr><td class="'.$cateStyle.'"><a '.$title.' href="'.sprintf($sFormat,$v["id"]).'&fid='.$v["fid"].'">'.$sep.$name.'</a>';	
		}
		else
		{
			$s .='<tr><td class="'.$cateStyle.'"><a '.$title.'  href="'.sprintf($sFormat,$v["id"]).'">'.$sep.$name.'</a>';
		}
		
		if(is_array($v["sub_cate"]) && count($v["sub_cate"]) > 0)
		{	
			$s .= GetCategoryTable($v["sub_cate"],$sFormat,$l+1,$SelectedID,$v["id"],&$flagAry);	
			if(array_key_exists($v["id"],$flagAry))
			{
				$flagAry[$ParentID] = $v["id"];	
			}
		}
		$s.='</td></tr>';
	}

	
	if(array_key_exists($ParentID,$flagAry) || $ParentID == $SelectedID || $ParentID==0) $display = '';
	else $display = ' style="display:none"';	

	$s='<table width="100%" border="0" cellSpacing="0" cellPadding="0" id="SubTb'.$ParentID.'"'.$display.'><tbody>'.$s.'</body></table>';
	
	return $s;
}

//$aryData:,$sFormat:ӵַʽ,$l:𼶱,$SelectedID:ǰѡƷID,$ParentID:ID,$flagAry:ӹϵ
function GetCategoryTable($aryData,$sFormat,$l,$SelectedID,$ParentID,&$flagAry)
{
	$s = '';
	$dot = '';
	$sep = '';
	$name = '';
	$display = '';
	$cateStyle = ''; //Ʋ˵ʽ
	if($flagAry == null) $flagAry = array(); //άһӵĸӹϵ
	
	for($i=0;$i<$l;$i++)
	{
		$sep .= '&nbsp;&nbsp;&nbsp;&nbsp;';	
	}
	//if($SelectedID == null || $SelectedID == "") $SelectedID = $aryData[0]["id"];
	if($ParentID == 0) $cateStyle = "menu_list";
	else  $cateStyle = "menu_list_sub";
	
	foreach($aryData as $k=>$v)
	{
		if(array_key_exists("publish",$v) && $v["publish"]==0 ) continue; //ǲ,ʾ
		if(array_key_exists("ispublish",$v) && $v["ispublish"]==0) continue; //ǲ,ʾ
		
		if(array_key_exists("sub_cate",$v) && GetProductNum($v) <=0 ) continue; //ƷĿ¼,Ŀ¼ûвƷĲʾ
		$v["namezh"]=AddAiralStyle($v["namezh"]);
		if($v["id"]==$SelectedID)
		{
			$name='<font color="#b68f2e" >'.$v["namezh"].'</font>';
			$flagAry[$ParentID] = $v["id"];
		}
		else
		{
			$name = $v["namezh"];	
		}
		
		//жʾƷ˵: urlfid
		if(array_key_exists("fid",$v))
		{
			$s .='<tr><td class="'.$cateStyle.'"><a href="'.sprintf($sFormat,$v["id"]).'&fid='.$v["fid"].'">'.$sep.$name.'</a>';	
		}
		else
		{
			$s .='<tr><td class="'.$cateStyle.'"><a href="'.sprintf($sFormat,$v["id"]).'">'.$sep.$name.'</a>';
		}
		
		if(is_array($v["sub_cate"]) && count($v["sub_cate"]) > 0)
		{	
			$s .= GetCategoryTable($v["sub_cate"],$sFormat,$l+1,$SelectedID,$v["id"],&$flagAry);	
			if(array_key_exists($v["id"],$flagAry))
			{
				$flagAry[$ParentID] = $v["id"];	
			}
		}
		$s.='</td></tr>';
	}

	
	if(array_key_exists($ParentID,$flagAry) || $ParentID == $SelectedID || $ParentID==0) $display = '';
	else $display = ' style="display:none"';	

	$s='<table width="100%" border="0" cellSpacing="0" cellPadding="0" id="SubTb'.$ParentID.'"'.$display.'><tbody>'.$s.'</body></table>';
	
	return $s;
}
//ȡĿ¼IDб:$aryData:Ŀ¼,$id:ڵID
function GetCategoryTreeIDS($aryData,$id,$publish=true)
{
	$vFalse = false;
	$s = SearchCategory($aryData,$id,$publish,&$vFalse);
	
	if(strlen($s)>0)
		$s = substr($s,0,strlen($s)-1);
	
	return $s;	
}
//Ŀ¼IDб:$aryData:Ŀ¼,$id:ڵID,$getFlag:Ƿҵڵıʶ
function SearchCategory($aryData,$id,$publish,&$getFlag)
{
	$s = '';
		
	foreach($aryData as $k=>$v)
	{	
		//ؽڵ	
		if($v["publish"] == 0 && $publish) continue;
		
		//ҵڵ,ȱ,ֵֹͣܽڵӱ(ע:$id==0ʱǲ,ID)
		if($v["id"] == $id || $id==0)
		{
			$s .= $v["id"].',';
			
			if($id > 0)	 $getFlag = true; 
			
			if(is_array($v["sub_cate"]) && count($v["sub_cate"]) > 0)
			{
				$s .= GetCategoryIDS($v["sub_cate"]); 	
			}
		}
		
		//Ƿ±
		if($getFlag == true)
		{
			break;
		}		
		else
		{
			if(is_array($v["sub_cate"]) && count($v["sub_cate"]) > 0)
			{
				$s .= SearchCategory($v["sub_cate"],$id,$publish,&$getFlag); 	
			}
		}
	}	
	return $s;	
}
//Ŀ¼ӽڵIDб:$aryData:Ŀ¼,$Publish:Ƿ
function GetCategoryIDS($aryData,$Publish = true)
{
	$s = '';
	foreach($aryData as $k=>$v)
	{		
		//ؽڵ	
		if($v["publish"] == 0 && $Publish) continue;
		
		$s .= $v["id"].',';
		if(is_array($v["sub_cate"]) && count($v["sub_cate"]) > 0)
		{
			$s .= GetCategoryIDS($v["sub_cate"]); 	
		}	
	}
	return $s;
}
//Ŀ¼ӽڵ:$aryData:Ŀ¼,$Publish:Ƿ
function GetCategoryAry($aryData,$Publish = true)
{
	$ary = array();
	foreach($aryData as $k=>$v)
	{		
		//ؽڵ	
		if($v["publish"] == 0 && $Publish) continue;
		
		$ary[] = $v["id"];
		if(is_array($v["sub_cate"]) && count($v["sub_cate"]) > 0)
		{
			array_merge($ary,GetCategoryIDS($v["sub_cate"])); 	
		}	
	}
	return $ary;
}
//ȡIDб()
function GetHiddenCategoryIDS($aryData)
{
	$s = '';	
	foreach($aryData as $k=>$v)
	{
		if($v["publish"] == 0)
			$s .= $v["id"].",". GetCategoryIDS($v["sub_cate"],false);
	}
	if(strlen($s)>0)
		$s = substr($s,0,strlen($s)-1);
		
	return $s;
}

function GetSettingAry()
{
	global $_categories,$db;
	
	$arySetting = array();
	foreach($_categories as $k => $v)
	{
		if($v["publish"]==0) continue;
		$cids = '';
		if(is_array($v["sub_cate"]) && count($v["sub_cate"]) >0)
		{
			$cids = GetCategoryIDS($v["sub_cate"]);		
		}
		if(strlen($cids)>0)
			$cids = $cids.$v["id"];
		else
			$cids = $v["id"];		
		
		/*$sql = "SELECT ps.`id`, ps.`name`,ps.`namezh` FROM `product` p,`p_setting` ps, `product_category` pc, `category` c WHERE pc.`category_id` IN(".$cids.") AND pc.`category_id` = c.`id` AND pc.`product_id`=p.`id` AND c.`publish`=1 AND ps.`ispublish`=1 AND ps.`id`=p.`setting_id` GROUP BY ps.`id` ORDER BY ps.`name`";*/
		$sql="SELECT ps.`id`, ps.`name`,ps.`namezh` FROM `p_setting` ps,`product_p_setting` pps,`product_category` pc,`product` p WHERE ps.`id`=pps.`setting_id` AND ps.`ispublish`=1 AND pc.`product_id`=pps.`product_id` AND pc.`category_id` IN(".$cids.") AND  p.`id`=pc.`product_id` AND p.`hidden_flag`=0  GROUP BY ps.`id` ORDER BY ps.`name`";
		
		$query = $db->query($sql);
		while($rs = $db->fetch_array($query))
		{
			$v["setting"][] = $rs;
		}
		$arySetting[] = $v;
	}	
	return $arySetting;
}

//ȡSettginʾ˵,$categoryid:ǰƷID,$settingid:ǰSettingid
function GetSettingMenu($arySetting,$toUrl,$categoryid,$settingid)
{
	$s = '';
	$ss ='';
	$cids = '';
	foreach($arySetting as $k => $v)
	{
		if($v["publish"]==0) continue;
		$ary = array();
		if(is_array($v["sub_cate"]) && count($v["sub_cate"]) >0)
		{
			$ary = GetCategoryAry($v["sub_cate"]);		
		}
        $v["namezh"]=AddAiralStyle($v["namezh"]);
		//жҪںforeachǰ
		if($v["id"]==$categoryid)
		{
			$name='<font color="#b68f2e" >'.$v["namezh"].'</font>';
		}
		else
		{
			$name = $v["namezh"];		
		}
		$ss = '';
		foreach($v["setting"] as $kk => $vv)
		{
		$vv["namezh"]=AddAiralStyle($vv["namezh"]);
			if($vv["id"]==$settingid)
			{
				$name = $v["namezh"];
				$name2='<font color="#b68f2e" >'.$vv["namezh"].'</font>';
			}
			else
			{
				$name2 = $vv["namezh"];		
			}
			$ss .= '<tr><td class="menu_list_sub"><a href="'.sprintf($toUrl,$v["id"],$vv["id"]).'">&nbsp;&nbsp;&nbsp;&nbsp;'.$name2.'</a></td></tr>';
		}
		
		$s .= '<tr><td class="menu_list"><a href="'.sprintf($toUrl,$v["id"],0).'">'.$name.'</a>';
		if($ss !='')
		{
			if($v["id"]==$categoryid || in_array($categoryid,$ary))
			{
				$displey='';
			}
			else
			{
				$displey=' style="display:none;"';
			}
			$s .= '<table width="100%" border="0" cellSpacing="0" cellPadding="0" id="SubTb'.$v["id"].'"'.$displey.'><tbody>'.$ss.'</body></table>';
		}
		$s .= '</td></tr>';
	}
	$s ='<table width="100%" border="0" cellSpacing="0" cellPadding="0"><tbody>'.$s.'</body></table>';	
	return $s;
}
//ȡCollection,Styleλ:$aryData:;$selectID:ǰѡеID,$rootUrl:ǰ˵ַ,$rootName:ǰ˵ַʾ,$paramName:ַв,$positionName:صĵֵ
//,ʾstyleid Ϊ1ĲƷб:GetPositionLink($_style,1,'style.php','Style/Porid','styleid',&$cateNaem);
//edit by martin 2010 - 12 - 8
function GetPositionLink($aryData,$selectID,$rootUrl,$rootName,$paramName,&$positionName)
{
	global $jansen_type,$jansen_uid;
	
	$toUrl = 'product_photo_list.php?'.$paramName.'=';
	if($jansen_type > 0 && $jansen_uid)
	{
		$toUrl = 'product_list.php?'.$paramName.'=';	
	}
	
	$s = '<div class="position" id="ProductPosition"><a href="index.php">首页</a>';
	$vSelected = null;
	foreach($aryData as $k => $v)
	{
		if($v["id"] == $selectID)
		{
			$vSelected = $v;	
		}
	}
	if($rootUrl != '' && $rootName != '')
	{
		$s .= ' &gt; <a href="'.$rootUrl.'">'.$rootName.'</a>';
	}
	
	if($vSelected !=null)
	{
	  
		$s .= ' &gt; <a href="'.$toUrl.$vSelected["id"].'">'.$vSelected["namezh"].'</a>';		
		$positionName = $vSelected["namezh"];
		
	}

	$s .= '</div>';

	return $s;
}
//ȡSettingĵǰλDIV
function GetSettingPositionLink($aryData,$toUrl,$categoryid,$settingid,&$positionName)
{
	$s = '<div class="position" id="ProductPosition"><a href="index.php">首页</a> &gt; <a href="setting.php">配套</a>';
	$found = false;
	foreach($aryData as $k => $v)
	{
		if($v["publish"]==0) continue;
		if($found) break;
		
		if($v["id"] == $categoryid)
		{
		       $v["namezh"]=AddAiralStyle($v["namezh"]);
			if($settingid >0)
			{
				$s .= ' &gt; <a href="'.sprintf($toUrl,$categoryid,0).'">'. $v["namezh"].'</a>';
			}
			else
			{
			   
				$s .= ' &gt; '. $v["namezh"];
				$positionName = $v["namezh"];
				break;
			}
		}
		
		foreach($v["setting"] as $kk => $vv)
		{
			if($vv["id"] == $settingid)
			{
			       $vv["namezh"]=AddAiralStyle($vv["namezh"]);
				$s .= ' &gt; <a href="'.sprintf($toUrl,$categoryid,$vv["id"]).'">'.$vv["namezh"].'</a>';
				$positionName = $vv["namezh"];
				$found = true;
				break;
			}
		}
	}
	$s .= '</div>';
	
	return $s;
}

//òƷǰλDIV
function GetProductCatePositionDiv($aryData,$selectID,&$tName)
{
 
	global $jansen_type,$jansen_uid;
	
	$toUrl = 'product_photo_list.php?categoryid=%d';
	if($jansen_type > 0 && $jansen_uid)
	{
		$toUrl = 'product_list.php?categoryid=%d';	
	}
	$tGetFlag = false;
	$str = explode('|',TravalCategory($aryData,$selectID,$toUrl,&$tGetFlag));
	if(count($str)>0)
		$tName = $str[1];
	
	
	//$s = '<div class="position" id="ProductPosition"><a href="index.php">Home</a> &gt; <a href="products.php">Product</a>';
	$s = '<div class="position" id="ProductPosition"><a href="index.php">首页</a> &gt; <a href="products.php">产品</a>';
	$s .= $str[0];
	$s .= '</div>';
	
	return $s;
}
function TravalCategory($aryData,$selectID,$toUrl,&$getFlag)
{
	$s = '';
	foreach($aryData as $k => $v)
	{
		if($v["publish"]==0) continue;
		
		if($v["id"] == $selectID)
		{
		     $v["namezh"]=AddAiralStyle($v["namezh"]);
			$s = ' &gt; <a href="'.sprintf($toUrl,$v["id"]).'">'.$v["namezh"].'</a>|'.$v["namezh"];
			$getFlag = true;
			break;	
		}	
		if(is_array($v["sub_cate"]) && count($v["sub_cate"]) >0)
		{
			$s .= TravalCategory($v["sub_cate"],$selectID,$toUrl,&$getFlag);		
			if($getFlag)
			{
			    $v["namezh"]=AddAiralStyle($v["namezh"]);
				$s = 	' &gt; <a href="'.sprintf($toUrl,$v["id"]).'">'.$v["namezh"].'</a>'.$s;
				break;
			}
		}
	}
	
	return $s;	
}

function GetBannerImg($str)
{
	return '<div class="bigtitle">'.$str .'</div>';
}

//ȡָƷµĲƷ:$aryDataĿ¼
function GetProductNum($node)
{
	global $db;
	
	if($node["id"] == 10001)
	{
		$sql = "SELECT p.`id` from `product_category` pc INNER JOIN `product` p ON pc.`product_id` = p.`id` INNER JOIN `category` c ON pc.`category_id`=c.`id`  WHERE p.`hidden_flag` = 0 AND p.`new_flag`=1 AND c.`publish` = 1";
		$row_num = $db->num_rows($db->query($sql));	
		return $row_num;
	}
	else
	{
		$cids="";
		if(is_array($node["sub_cate"]) && count($node["sub_cate"])>0)
			$cids = GetCategoryIDS($node["sub_cate"],true);
		
		if($cids != "") $cids = $cids.$node["id"];
		else $cids = $node["id"];	
		
		$sql = "SELECT p.`id` from `product_category` pc INNER JOIN `product` p ON pc.`product_id` = p.`id` WHERE p.`hidden_flag` = 0 AND pc.`category_id` IN(".$cids.")";
		$row_num = $db->num_rows($db->query($sql));
		return $row_num;
	}
}

function DomaiJump()
{
$domain_EN="jansenfurniture.imakertechnology.com";
if(($_SERVER['HTTP_HOST']==$domain_EN)or($_SERVER['HTTP_HOST']=="www".$domain_EN))
{
    //$go=$_SERVER['HTTP_HOST']."/index.php";
	$go="http://".$domain_EN."/index.php";  
	header("Location: $go");		 
}

}

function getWebMasterEmails($va)
{
  global $_SystemAll,$db;	
  $systems=array();
  $str="info@jansenfurniture.com.hk";
  if(isset($_SystemAll))
  {
    $systems=explode(",", $_SystemAll[$va]);
  }
 return  $systems[0];
}

function getCartDataFirst()
{
           global $db,$jansen_uid;
		 
			$sql = "select cart from cart_record where uid = '". $jansen_uid."'";	
			$cart_t = $db->get_one($sql);			
			if (!empty($cart_t)) 
			{
			   
				$cart = new cart();
				$cart_g = unserialize($cart_t['cart']);
				 
				if (empty($cart_g->myCart)) {
					@saveCart($db, $jansen_uid, "");			
					$_SESSION["myCart"] = $cart_g->myCart;
				} else {
					$_SESSION["myCart"] = $cart_g->myCart;
					$cart->update();
					
				}	
				
			}

}

function AddAiralStyle($name)
{
 global $English_Txt;
 $ns=$name;
 if(mb_strlen("$name",'utf-8')!=strlen("$name"))
 {
   $ns=$name;
 }
 else
 {
   $ns="<span class='EnTextFamily'>".$name."</span>";
 }
 
 //echo "$name"." : ".mb_strlen("$name",'utf-8')." ".strlen("$name")."<br/>"; 
 
  /*if(in_array(trim($name),$English_Txt))
		{
		  $ns="<span class='EnTextFamily'>".$name."</span>";		
		}
		else
		{
		  $ns=$name;
		}*/
	
return $ns;
}
?>
